package com.itcast.demoone.fragment

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.itcast.demoone.R


class ListFragment : Fragment() {

    // 声明一个变量来保存实现了OnItemSelectedListener接口的监听器实例
    private var listener: OnItemClickListener? = null

    // 1. 定义一个接口
    interface OnItemClickListener {
        fun onItemClick(itemId: Int)
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_list, container, false)
    }

    // 在Fragment的视图创建完成后调用，用于初始化视图组件
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        view.findViewById<Button>(R.id.item1).setOnClickListener {
            listener?.onItemClick(1)
        }

        view.findViewById<Button>(R.id.item2).setOnClickListener {
            listener?.onItemClick(2)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnItemClickListener) {
            // 2. 创建接口对象
            listener = context
        }
    }

    override fun onDetach() {
        super.onDetach()
        // 3. 销毁接口对象
        listener = null
    }
}